<template>
	<div class="wrapper">
		<u-form label-width="200" :model="form" ref="uForm">
			<div class="column">
				<div class="flag-title light-color">基础信息</div>
				<u-form-item required :border-bottom="false" prop="merchant_name" label="商铺名称"><u-input
						v-model="form.merchant_name" :custom-style="defaultInputStyle" /></u-form-item>
				<u-form-item required :border-bottom="false" prop="company_name" label="公司名称"><u-input
						v-model="form.company_name" :custom-style="defaultInputStyle" /></u-form-item>
				<u-form-item required :border-bottom="false" prop="merchant_address" label="公司所在地">
					<div @click="showPicker()" style="margin-right: 30rpx;">选择</div>
					<u-input disabled :custom-style="defaultInputStyle" v-model="form.companyAddressIdPath" />
				</u-form-item>
				<u-form-item required :border-bottom="false" prop="detail_address" label="公司详细地址"><u-input
						:custom-style="defaultInputStyle" v-model="form.detail_address" /></u-form-item>
				<u-form-item required :border-bottom="false" prop="longitude" label="经度"><u-input
						:custom-style="defaultInputStyle" v-model="form.longitude" /></u-form-item>
				<u-form-item required :border-bottom="false" prop="latitude" label="纬度 "><u-input
						:custom-style="defaultInputStyle" v-model="form.latitude" /></u-form-item>
				<u-form-item required :border-bottom="false" prop="contact_name" label="联系人姓名"><u-input
						:custom-style="defaultInputStyle" v-model="form.contact_name" /></u-form-item>
				<u-form-item required :border-bottom="false" prop="contact_mobile" label="联系人电话"><u-input type="number"
						:custom-style="defaultInputStyle" v-model="form.contact_mobile" /></u-form-item>
				<u-form-item :border-bottom="false" prop="merchant_img" label="商户图片URL" required>
					<div>
						<u-upload :file-list="merchantimgs" :header="{ 'ba-user-token': storage.getAccessToken(),server:true }"
							:action="action" width="200" @on-uploaded="onUploaded($event, 'merchant_img')" :max-count="1"
							:show-progress="false"></u-upload>

						<div class="tips">
							请压缩图片在2M以内，确保文字清晰以免上传或审核失败
						</div>
					</div>
				</u-form-item>
			</div>
			<div class="column">
				<div class="flag-title light-color">营业执照信息</div>
				<u-form-item required :border-bottom="false" prop="business_list" label="法定经营范围"><u-input
						:custom-style="defaultInputStyle" v-model="form.business_list" /></u-form-item>
				<u-form-item :border-bottom="false" prop="merchant_licence" label="营业执照电子版" required>
					<div>
						<u-upload :file-list="licencePhotoFileList"
							:header="{ 'ba-user-token': storage.getAccessToken(),server:true }" :action="action" width="200"
							@on-uploaded="onUploaded($event, 'merchant_licence')" :max-count="1" :show-progress="false"></u-upload>

						<div class="tips">
							请压缩图片在2M以内，确保文字清晰以免上传或审核失败
						</div>
					</div>
				</u-form-item>
			</div>
		</u-form>
		<div v-if="status !== 1" class="submit" :class="status === 0?'bgcecece':'bge87722cc'" @click="validatorStep1Form">提交
		</div>
		<m-city :provinceData="list" headTitle="区域选择" ref="cityPicker" @funcValue="getPickerParentValue" pickerSize="4">
		</m-city>
	</div>
</template>

<script>
	import {
		merchantManageapply,
		merchantManageinfoedit
	} from "@/api/entry";

	import city from "@/components/m-city/m-city.vue";
	import storage from "@/utils/storage.js";
	import {
		upload
	} from "@/api/common.js";
	import {
		getRegionsById
	} from "@/api/common.js";
	import * as RegExp from "@/utils/RegExp.js";
	import config from '@/config/api.js'
	export default {
		components: {
			"m-city": city
		},
		props: ["companyData", "status"],
		data() {
			return {
				storage,
				action: upload, //图片上传数据
				defaultInputStyle: {
					background: "#f7f7f7",
					padding: "0 20rpx",
					"border-radius": "10rpx",
				},
				licencePhotoFileList: [],
				form: {
					merchant_name: '',
					company_name: '',
					merchant_address: [],
					companyAddressIdPath: '',
					detail_address: '',
					contact_name: '',
					contact_mobile: '',
					merchant_img: [],
					business_list: '',
					merchant_licence: [],
					latitude: '',
					longitude: ''
				},
				merchantimgs: [],
				list: [{
					id: "",
					localName: "请选择",
					children: [],
				}, ],
				rules: {
					// 验证规则
					merchant_name: [{
						required: true,
						message: "请填写商铺名称"
					}],
					// 验证规则
					company_name: [{
						required: true,
						message: "请填写公司名称"
					}],
					merchant_address: [{
						required: true,
						message: "请选择公司所在地"
					}],
					detail_address: [{
						required: true,
						message: "请填写公司详细地址"
					}],
					contact_name: [{
						required: true,
						message: "请填写联系人姓名"
					}],
					contact_mobile: [{
							required: true,
							message: "请填写联系人电话"
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// this.$u.test.mobile()就是返回true或者false的
								return this.$u.test.mobile(value);
							},
							message: "手机号码不正确",
							// 触发器可以同时用blur和change
							trigger: ["change", "blur"],
						},
					],
					business_list: [{
						required: true,
						message: "请填写营业执照所示经营范围"
					}],
					merchant_licence: [{
						required: true,
						message: "请上传营业执照"
					}]

				},
				areaTree: []
			};
		},
		watch: {
			companyData: {
				handler(val) {
					const obj = {
						...val,
						companyAddressIdPath: ''
					}
					this.$set(this, "form", obj);
					if (val.id) {
						this.merchantimgs = [{
							url: config.buyer + val.merchant_img
						}]
						this.licencePhotoFileList = [{
							url: config.buyer + val.merchant_licence
						}]
						this.$nextTick(() => {
							this.getRegionsById()
						})
					}
					console.log(this.form, this.merchantimgs)
				},
				deep: true,
				immediate: true
			},
		},
		mounted() {
			if (this.status === null) {
				this.getRegionsById()
			}
			this.$refs.uForm.setRules(this.rules);
		},
		methods: {
			getRegionsById() {
				this.areaTree = uni.getStorageSync('areaTree') || []
				if (this.form.merchant_address) {
					const ids = this.form.merchant_address.split(',')
					const areaFlat = this.flattenAreaTreeRecursive(this.areaTree);
					const pathStr = areaFlat.filter(a => ids.includes(a.value + '')).map(a => a.label).join(
						',')
					this.form.companyAddressIdPath = pathStr
				}
			},
			flattenAreaTreeRecursive(tree, result = [], parentId = null) {
				// 遍历当前层级的每个节点
				tree.forEach(node => {
					// 复制节点并添加父级ID（可选）
					const item = {
						...node,
						parentId
					};
					// 添加到结果数组
					result.push(item);

					// 如果有子节点，递归处理
					if (node.children && node.children.length > 0) {
						this.flattenAreaTreeRecursive(node.children, result, node.value);
					}
				});

				return result;
			},
			// 图片上传
			onUploaded(lists, key) {
				let images = [];
				if (!this.form[key]) {
					this.form[key] = [];
				}
				console.log(lists)
				lists.forEach((item) => {
					images.push(item.response.data.file.url);
				});
				this.form[key].push(images[0]);
			},
			getPickerParentValue(e) {
				this.form.merchant_address = [];
				let name = "";
				e.forEach((item, index) => {
					if (item.value) {
						// 遍历数据
						this.form.merchant_address.push(item.value);
						if (index == e.length - 1) {
							name += item.localName;
						} else {
							name += item.localName + ",";
						}
						this.form.companyAddressIdPath = name;
					}
				});
			},
			// 显示三级地址联动
			showPicker() {
				console.log(this.$refs)
				this.$refs.cityPicker.show(this.areaTree);
			},
			validatorStep1Form() {
				if (this.status === 0 || this.status === 1) return
				this.$refs.uForm.validate(async (valid) => {
					console.log(valid);
					if (valid) {
						const params = {
							...this.form
						};
						params.merchant_address = params.merchant_address.toString();
						params.merchant_licence = params.merchant_licence.toString();
						params.merchant_img = params.merchant_img.toString();

						console.log(params)
						if (params.id) {
							this.merchantManageinfoedit(params)
							return
						}
						const res = await merchantManageapply(params);
						if (res.data.code === 1) {
							uni.showToast({
								title: "提交成功!",
								icon: "none",
							});
							this.$emit("callback");
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						}
					}
				});
			},
			merchantManageinfoedit(params) {
				merchantManageinfoedit(params).then(res => {
					if (res.data.code === 1) {
						uni.showToast({
							title: "提交成功!",
							icon: "none",
						});
						setTimeout(() => {
							this.$emit("callback");
						}, 1000)
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
					}
				})
			}
		},
	};
</script>
<style>
	/* page {
  background: #fff;
} */
</style>
<style lang="scss" scoped>
	@import url("./entry.scss");

	.column {
		padding: 32rpx;
		margin-bottom: 20rpx;
		background: #fff;
	}

	.submit {
		color: #fff;
		margin-top: 120rpx;
	}

	.tips {
		color: #999;
		font-size: 24rpx;
		line-height: 1.2;
		margin-top: 10rpx;
	}
</style>